<template>
  <view class="address-page">
    <view class="addr-search-bar">
      <uni-search-bar
        :focus="true"
        bg-color="var(--white)"
        radius="100"
        v-model="keywords"
        @confirm="search"
        @input="search"
        @cancel="cancel"
        @clear="clear">
      </uni-search-bar>
    </view>
    
    <view v-if="searching">
      <uni-list>
        <uni-list-item v-for="(p, idx) in places" 
          :title="p.placeName"
          :key="'p-l-' + idx"
          showArrow
          clickable
          @click="selectCity(p)">
          <template v-slot:header>
            <view class="place-icon-wrapper">
              <ai-icon type="icon-position" :size="16" color="var(--gray-2)"></ai-icon>
            </view>
          </template>
          <template v-slot:body>
            <view class="place-item-wrapper">
              <view class="place-title">
                <text
                  class="place-title-text"
                  v-for="(t,i) in p.keyLabel"
                  :class="{'key': t.match }"
                  :key="'t-k-' + i">{{t.value}}</text>
              </view>
            </view>
          </template>
        </uni-list-item>
      </uni-list>
    </view>
    
    <view class="search-nodata-wrapper" v-if="searching && places.length == 0">
      <tp-nodata-card
        :plain="true"
        title="暂时没有您指定条件的城市"
        sub-title="请尝试改变关键词重新搜索">
      </tp-nodata-card>
    </view>
    
    <view class="address-content" v-if="!searching">
      <view class="tab-wrapper">
        <scroll-view scroll-y="true" class="scroll-h-view" :scroll-with-animation="true">
          <view v-for="(p, idx) in addrTabs" 
            :id="'group-' + idx"
            :key="'tab-' + idx"
            class="scroll-view-item"
            :class="{active: activeIdx == idx, pre: activeIdx-1 == idx, next: activeIdx+1 == idx}"
            @click="onTabClick(idx)"
            >{{p}}</view>
        </scroll-view>
      </view>
      <view class="tab-content">
        <scroll-view scroll-y="true" class="scroll-h-view">
          <view class="history-box" v-if="historyCityList.length > 0">
            <view class="his-title-wrapper">
              <view class="his-title">历史选择</view>
              <ai-icon-button icon="icon-delete" :size="14" @click="clearHistory"></ai-icon-button>
            </view>
            <view class="his-city-box">
              <view class="his-city-item" v-for="(c, idx) in historyCityList"
                @click="selectCity({placeName:c})"
                :key="'his-c-' + idx">
                <view class="his-city">{{c}}</view>
              </view>
            </view>
          </view>
          
          <ai-section v-if="recPlaceList.length > 0" title="热门" bg-transparent></ai-section>
          <view class="img-address-box">
            <view v-for="(a, idx) in recPlaceList" class="addr-item" 
              @click="selectCity(a)"
              :key="'hot-addr-' + idx">
              <view class="pic-box" 
                :style="'background-image: url(' + a.mainPic + '); background-size:100% 100%'">
              </view>
              <text class="text">{{a.placeName}}</text>
              <label class="tag" v-if="a.recTag">{{a.recTag}}</label>
            </view>
          </view>
      
          <ai-section v-if="activeIdx > 0" :title="acitiveGroup" bg-transparent></ai-section>
          <view class="img-address-box" v-if="imgPlaceList.length > 0">
            <view v-for="(a, gidx) in imgPlaceList"
              class="addr-item"
              @click="selectCity(a)"
              :key="'img-addr-' + gidx">
              <view class="pic-box"
                :style="'background-image: url(' + a.mainPic + '); background-size:100% 100%'">
              </view>
              <text class="text">{{a.placeName}}</text>
            </view>
          </view>
          
          <ai-section v-if="textPlaceList.length > 0" title="更多地区" bg-transparent></ai-section>
          <view class="city-box" v-if="textPlaceList.length > 0" >
            <view v-for="(c, cidx) in textPlaceList"
              class="city-item"
              @click="selectCity(c)"
              :key="'text-addr-' + cidx">
              <view class="city">{{c.placeName}}</view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
  
</template>

<script>
  import { mapState  } from 'vuex';
  
  export default {
    data() {
      return {
        keywords: "",
        searching: false,
        places: [],
        
        activeIdx: 0,
        addrTabs: [],
        recPlaceList: [],
        imgPlaceList: [],
        textPlaceList: [],
        origin: "def"
      }
    },
    onLoad(options) {
      this.origin = options.origin || "def"
    },
    mounted() {
      this.initTabs()
      this.loadAddr()
    },
    computed: {
      ...mapState({
        historyCityList: state => state.address.hisCities
      }),
      acitiveGroup() {
        return this.addrTabs[this.activeIdx]
      }
    },
    methods: {
      initTabs() {
        let url = this.$urls.getApi("addrProv")
        this.$get(url).then(res => {
          let provList = res.module || []
          this.addrTabs.push("热门推荐")
          this.addrTabs.push(...provList)
        })
      },
      onTabClick(idx) {
        this.activeIdx = idx
        this.loadAddr()
      },
      clearHistory() {
        this.$store.dispatch("address/clear")
      },
      loadAddr() {
        this.resetPlaceData()
        let idx = this.activeIdx
        if (idx == 0) {
          this.queryAllHots()
        } else {
          this.queryGroup(idx)
        }
      },
      queryAllHots() {
        let url = this.$urls.getApi("addrHot")
        this.$get(url).then(res => {
          let data = res.module
          this.recPlaceList.push(...data)
        })
      },
      queryGroup(idx) {
        let url = this.$urls.getApi("addrGroup")
        let groupCode = this.addrTabs[idx]
        this.$get(url, {
          data: {groupCode}
        })
        .then(res => {
          let group = res.module
          const {recPlaces=[], imgPlaces=[], textPlaces=[]} = group
          this.recPlaceList.push(...recPlaces)
          this.imgPlaceList.push(...imgPlaces)
          this.textPlaceList.push(...textPlaces)
        })
      },
      resetPlaceData() {
        let recLen = this.recPlaceList.length
        this.recPlaceList.splice(0, recLen)
        let imgLen = this.imgPlaceList.length
        this.imgPlaceList.splice(0, imgLen)
        let textLen = this.textPlaceList.length
        this.textPlaceList.splice(0, textLen)
      },
      selectCity(p) {
        let curCity = {
          city: p.placeName,
          origin: this.origin
        }
        this.$store.dispatch("address/addCity", curCity)
        .then(res => {
          uni.navigateBack({
            success(res) {
              console.log("navigateBack success")
              uni.$emit("handClickAddress", curCity)
            }
          })
        })
      },
      search(keywords) {
        this.places.splice(0, this.places.length)
        if (!keywords) {
          this.searching = false
          return
        }
        this.searching = true
        
        let url = this.$urls.getApi("addrSearch");
        this.$get(url, {
          data: {keywords: keywords}
        })
        .then(res => {
          let places = res.module || []
          places.map((p) => {
            let label = p.cityName + "·" + p.placeName
            p.keyLabel = this.$tools.splitKeywords(label, keywords, 21)
          })
          this.places.push(...places)
        })
      },
      clear() {
        this.searching = false
      },
      cancel() {
        this.searching = false
        uni.navigateBack();
      },
    }
  }
</script>

<style lang="scss">
  @import "@/styles/_var.scss";
  
  $tab-width: 80px;
  
  .address-page {
    position: relative;
    background-color: var(--white);
    display: flex;
    flex-direction: column;
  }
  
  .addr-search-bar {
    background-color: $body-bg-gray;
    border-bottom: 1px solid var(--gray-8);
  }

  .address-content {
    position: relative;
    display: flex;
    flex-direction: row;
  }
  
  .tab-wrapper {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    min-height: 100vh;
    width: $tab-width;
    background-color: var(--white);
    
  }
  
  .tab-content {
    position: absolute;
    top: 0;
    left: $tab-width;
    bottom: 0;
    width: calc(100vw - $tab-width);
    min-height: 100vh;
    background-color: var(--white);
  }

  .scroll-h-view {
    height: 100%;
    &::-webkit-scrollbar {
        display: none;  
        width: 0 !important;  
        height: 0 !important;  
        -webkit-appearance: none;  
        background: transparent;  
    }
  }
  
  .scroll-view-item {
    height: 48px;
    line-height: 48px;
    text-align: center;
    font-size: $font-size-md;
    transition: 0.2s;
    background-color: var(--gray-8);
    
    &.active {
      background-color: var(--white);
    }
    
    &.pre {
      border-bottom-right-radius: $border-radius-sm;
    }
    
    &.next {
      border-top-right-radius: $border-radius-sm;
    }
  }
  
  .history-box {
    padding-top: $gutter;
    position: relative;
    border-bottom: 1px solid var(--gray-7);
    
    .his-title-wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      padding-right: $gutter;
      
      .his-title {
        padding: 0 $gutter 6px;
        font-size: $font-size-md;
        font-weight: normal;
      }
    }
  }

  .his-city-box {
    display: flex;
    flex-wrap: wrap;
    padding-left: $gutter;

    .his-city-item {
      box-sizing: border-box;
      padding: 0 $gutter $gutter 0;

      .his-city {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: var(--gray-7);
        padding: 0 6px;
        height: 24px;
        border-radius: 6px;
        font-size: $font-size-sm;
        color: var(--gray-1);
        cursor: pointer;
      }
    }
  }
  
  .img-address-box {
    display: flex;
    flex-wrap: wrap;
    padding-left: $gutter;

    .addr-item {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-sizing: border-box;
      padding: 0 $gutter $gutter 0;
      flex-basis: 50%;
      cursor: pointer;

      .pic-box {
        position: relative;
        border-radius: 6px;
        overflow: hidden;
        height: 0;
        width: 100%;
        padding-bottom: 67%;
        transition: 0.3s;
      }

      .text {
        padding-top: 6px;
        color: var(--gray-1);
        font-size: $font-size-md;
      }

      .tag {
        position: absolute;
        top: 0;
        left: 0;
        padding: 0 4px;
        background-color: var(--brand-2);
        border-radius: 6px 0 6px 0;
        height: 16px;
        color: var(--white);
        font-size: $font-size-xs;
      }
    }
  }
  
  .city-box {
    display: flex;
    flex-wrap: wrap;
    padding-left: $gutter;

    .city-item {
      flex-basis: 50%;
      box-sizing: border-box;
      padding: 0 $gutter $gutter 0;

      .city {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: var(--gray-7);
        height: 36px;
        width: 100%;
        border-radius: 6px;
        font-size: $font-size-md;
        color: var(--gray-1);
        cursor: pointer;
      }
    }
  }
  
  .search-nodata-wrapper {
    min-height: calc(100vh - 60px);
  }
  .place-icon-wrapper {
    margin-right: $gutter * 0.5;
  }
  
  .place-item-wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    
    .place-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      
      overflow: hidden;
      text-overflow: ellipsis;
      word-wrap: nowrap;
      
      .place-title-text {
        font-size: $font-size-md;
        color: var(--gray-2);
        overflow: hidden;
        text-overflow: ellipsis;
        word-wrap: nowrap;
        
        &.key {
          color: var(--brand-2);
        }
      }
    }
  }
  
</style>